// 预定义
var timetd = null;// 当前正在编辑的时间单元格对象
var today = "";// 今日的工作日志缓存数据（若未提交过则为空）
var images = "";

//页面载入初始化
$( "body" ).ready( function( e )
{
	init_style( $( "#__TIME_SELECTER > table" ), "9:00", "23:00" );

	$( "#__TIME_SELECTER" ).bind( "click", function( e )
	{
		e.stopPropagation();
	} );

	$( document ).bind( "click", function( e )
	{
		$( "#__TIME_SELECTER" ).hide();
		body_get_focus( e );
	} );

	$( "td[rel=select_time]" ).bind( "click", function( e )
	{
		bind_select_timer( e, $( this ) );
	} );

	$( "body" ).bind( "keyup", bodyKeyupHandler );
	editarea_vailable( false );
	( $.browser.msie ? $( "body" ) : $( window ) ).bind( { focusin: function( e )
	{
		editarea_vailable( true );
	}, focusout: function( e )
	{
		editarea_vailable( false );
		hide_time_selecter();
	} } );

	// 初始化数据库读出来的数据
	init_with_database();
	init_table_sh_click();
	init_imgupload_model();
	init_imgselect_model();
	init_timer( timer_handler, timer_second_handler, 300 );
} );

function timer_second_handler( ts )
{
	$( "#second" ).text( ts );
}

function timer_handler()
{
	var t = $( "#__WORK_TABLE" );
	submit_work( t );
}

function editarea_vailable( val )
{
	//	$( "#container" ).alpha( 0.5 );
	$( "#KEY_VAILABLE" ).text( val ? "可用" : "不可用" );
}

function init_imgselect_model()
{
	parent.set_selected_fn( selected_complete );
}

function selected_complete( value )
{
	upload_complete( value );
}

function init_imgupload_model()
{
	parent.set_complete_fn( upload_complete );

	$( "#__IMGLST_ROW .imglist > li.add" ).bind( "click", function()
	{
		parent.up_open();
	} );
}

function upload_complete( value )
{
	var pa = value;
	var add = $( "#__IMGLST_ROW .imglist > li.add" );
	var mw = 180;
	var mh = 150;

	// 上传完成时返回数据要判断是否为图片还是文档，分开处理
	for( var i = 0; i < pa.length; i++ )
	{
		var d = $.parseJSON( pa[ i ] );
		var exist = $( "#__IMGLST_ROW .imglist > li > img[title='" + d.url + "']" ).length > 0;

		if( !exist )
		{
			var html = "";
			var ext = d.ext;

			// 兼容旧数据
			if( d.ext == undefined )
			{
				ext = d.name.split( "." )[ 1 ];
			}

			if( "jpg;gif;png".indexOf( ext ) > -1 )
			{
				// 图片
				var dw = d.width;
				var dh = d.height;

				if( dw > mw )
				{
					dw = mw;
					dh = ( mw / d.width ) * d.height;
				}

				if( dh > mh )
				{
					dh = mh;
					dw = ( mh / d.height ) * d.width;
				}
				html = "<li rel='" + pa[ i ] + "' style='line-height:180px;*font-size:157px;'><img title='"
						+ d.url + "' width='" + dw + "' height='" + dh + "' src='" + d.url + "' /></li>";
			}
			else
			{
				// 其它文档
				var img_url = "";

				switch( d.ext ) {
					case "doc":
					case "docx":
						img_url = "img/ext/doc.png";
						break;
					case "xls":
					case "xlsx":
						img_url = "img/ext/xls.png";
						break;
					case "ppt":
					case "pptx":
						img_url = "img/ext/ppt.png";
						break;
					case "vsd":
					case "vsdx":
						img_url = "img/ext/vsd.png";
						break;
					case "pdf":
						img_url = "img/ext/pdf.png";
						break;
					case "txt":
						img_url = "img/ext/txt.png";
						break;
				}

				var name = d.name.substr( 0, d.name.lastIndexOf( "." ) );
				if( name.length > 12 )
					name = name.substr( 0, 12 ) + "...";

				html = "<li rel='" + pa[ i ] + "'><img title='" + d.url + "' src='" + img_url
						+ "' /><span style='height:25px;line-height:25px;display:block;'>" + name
						+ "</span></li>";
				//html = "<li rel='" + pa[ i ] + "'><img title='" + d.url + "' src='" + img_url + "' /></li>";
			}

			add.before( html );

			var lis = $( "#__IMGLST_ROW .imglist > li[class!=add]" );
			lis.eq( lis.length - 1 ).one( "dblclick", function( e )
			{
				$( this ).remove();
			} );
		}
	}
}

/**
 * 初始化以fields为样式名的标题栏具备隐藏和显示其它表格行的功能
 */
function init_table_sh_click()
{
	$( "table:not([rel*=nosh])" ).each( function()
	{
		var th = $( this ).find( "tr[class=fields] th" );

		th.css( "cursor", "pointer" );
		th.bind( "click", function()
		{
			var trs = $( this ).parent().parent().find( "tr[class!=fields]" );
			trs.eq( 0 ).css( "display" ) == "none" ? trs.show() : trs.hide();
		} );
	} );
}

function init_with_database()
{
	if( today != "" && $.isArray( today ) )
	{
		var t = $( "#__WORK_TABLE" );

		for( var i = 0; i < today.length; i++ )
		{
			var d = today[ i ];
			append_work( t, d.time, d.title, d.content );
		}
	}

	if( images != "" )
	{
		upload_complete( images.split( "|||" ) );
	}
}

function body_get_focus( e )
{
	if( !$.browser.msie )
	{
		e.stopPropagation();
		$( "body" ).focus();
	}
}

function init_style( t, s, e )
{
	var ma = s.split( ":" );
	var tma = e.split( ":" );
	var h = parseInt( ma[ 0 ] );
	var th = parseInt( tma[ 0 ] );
	var size = 6;

	var head = "";
	var hh = "";
	var tt = "";
	var id = "";
	var bgc = "";
	for( var i = h; i < th; i++ )
	{
		head += "<th colspan='"
				+ size
				+ "' width='60' style='text-align:center;color:#fff;background:#95B3D7;border-color:#f3f3f3;'>"
				+ i + "点</th>";

		for( var hi = 0; hi < size; hi++ )
		{
			id = "h" + i + ":" + ( hi == 0 ? "00" : hi * 10 );
			bgc = i >= 10 && i <= 20 || ( i == 9 && hi >= 3 ) || ( i == 18 && hi < 3 ) ? ( i < 12 ? "#CCC0DA"
					: ( i >= 13 ? "#CCC0DA" : "#DCEEA6" ) ) : "#DBE5F1";
			if( i >= 18 && i < 19 )
				bgc = "#DCEEA6";

			hh += "<td id='" + id + "' style='background:" + bgc
					+ ";padding:0;width:10px;height:10px;border-color:#f3f3f3;'></td>";

			id = "t" + i + ":" + ( hi == 0 ? "00" : hi * 10 );
			tt += "<td id='"
					+ id
					+ "' style='background:#f9f9f9;padding:0;width:10px;height:20px;border-color:#f3f3f3;'></td>";
		}
	}

	t.append( "<tr>" + head + "</tr><tr>" + hh + "</tr><tr>" + tt + "</tr>" );
	t.find( "td[id^=t]" ).bind( "click", time_click_handler );
}

//--------------------------------------------------------------------------
//
//	时间选择器操作
//
//--------------------------------------------------------------------------

var stime = null;// 选择的开始时间单元格
var etime = null;// 选择的结束时间单元格

/**
 * 当打开时间选择器时，初始化当前已经选择的时间段到选择器
 * 
 * @param td
 */
function init_to_timer( td )
{
	var tb = $( "#__TIME_SELECTER > table" );

	var ts = td.find( "span" ).text();
	var ta = ts.split( "-" );

	if( ts != "" && ta.length == 2 )
	{
		var sid = "t" + ta[ 0 ];

		stime = tb.find( "td[id='" + sid + "']" );

		var de = new Date();
		var ea = ta[ 1 ].split( ":" );
		de.setHours( ea[ 0 ], parseInt( ea[ 1 ] ) - 10 );

		var et = de.getHours() + ":" + ( de.getMinutes() == 0 ? "00" : de.getMinutes() );
		etime = tb.find( "td[id='t" + et + "']" );
	}
	else
	{
		stime = null;
		etime = null;
	}

	update_selected_time( tb );
}

function time_click_handler( e )
{
	var td = $( this );// 时间选择器上单击的单元格
	var tb = $( "#__TIME_SELECTER > table" );

	if( stime == null )
	{
		stime = td;
	}
	else if( stime != null && etime != null )
	{
		stime = td;
		etime = null;
	}
	else
	{
		if( td.index() < stime.index() )
		{
			etime = stime;
			stime = td;
		}
		else
		{
			etime = td;
		}
	}

	// 更新选中时间段表现
	update_selected_time( tb );
	update_selected_text();
	update_selected_text_hour();
}

/**
 * 根据当前选定的时间单元，来处理选择器的外观表现
 * 
 * @param t 时间选择器表格对象
 */
function update_selected_time( t )
{
	if( stime == null && etime == null )
	{
		t.find( "td[id^=t]" ).each( function()
		{
			$( this ).css( "background-color", "#f9f9f9" );
		} );
	}
	else
	{
		var si = -1;
		var ei = -1;

		if( stime != null )
		{
			si = stime.index();
			stime.css( "background-color", "#C6EFCE" );
		}

		if( etime != null )
		{
			ei = etime.index();
			etime.css( "background-color", "#C6EFCE" );
		}
		else
		{
			t.find( "td[id^=t]" ).each( function()
			{
				if( stime != null && stime.index() != $( this ).index() )
					$( this ).css( "background-color", "#f9f9f9" );
			} );
		}

		if( stime != null && etime != null )
		{
			t.find( "td[id^=t]" ).each( function()
			{
				var idx = $( this ).index();

				if( idx >= si && idx <= ei )
				{
					$( this ).css( "background-color", "#C6EFCE" );
				}
				else
				{
					$( this ).css( "background-color", "#f9f9f9" );
				}
			} );
		}
	}
}

/**
 * 根据选定的时间单元，更新显示时间段到表格中
 */
function update_selected_text()
{
	if( stime != null && etime != null )
	{
		var sa = stime.attr( "id" ).substr( 1 ).split( ":" );
		var ea = etime.attr( "id" ).substr( 1 ).split( ":" );

		var st = sa[ 0 ] + ":" + sa[ 1 ];
		var et = "";

		var ds = new Date();
		var de = new Date();

		ds.setHours( sa[ 0 ], sa[ 1 ] );
		de.setHours( ea[ 0 ], parseInt( ea[ 1 ] ) + 10 );
		et = de.getHours() + ":" + ( de.getMinutes() == 0 ? "00" : de.getMinutes() );

		timetd.find( "span" ).text( st + "-" + et );
	}
	else
	{
		timetd.find( "span" ).text( "" );
	}
}

/**
 * 根据最新设置的时间（例："9:10-10:20"），计算两者之间的小时数
 */
function update_selected_text_hour()
{
	var ts = timetd.find( "span" ).text();
	var ta = ts.split( "-" );

	if( ts != "" && ta.length == 2 )
	{
		var sa = ta[ 0 ].split( ":" );
		var ea = ta[ 1 ].split( ":" );
		var ds = new Date();
		var de = new Date();

		ds.setHours( sa[ 0 ], sa[ 1 ] );
		de.setHours( ea[ 0 ], ea[ 1 ] );

		var t = de.getTime() - ds.getTime();// 毫秒
		timetd.find( "p" ).text( "总计 " + ( Math.ceil( t / 1000 / 3600 * 10 ) / 10 ) + " 小时 " );
	}
	else
	{
		timetd.find( "p" ).text( "" );
	}
}

//--------------------------------------------------------------------------

function show_time_selecter( p )
{
	timetd = p;

	var d = $( "#__TIME_SELECTER" );
	var pos = p.offset();
	var top = pos.top + p.outerHeight() + 2;

	d.hide();
	d.css( { left: pos.left + 5, top: top + 5 } );
	d.animate( { top: top, opacity: 'show' }, 200 );
}
function hide_time_selecter()
{
	$( "#__TIME_SELECTER" ).hide();
}

function bodyKeyupHandler( e )
{
	var t = $( "#__WORK_TABLE" );

	if( e.ctrlKey && e.which == 13 )
	{
		submit_work( t );
	}
	else if( e.which == 119 )// F8
	{
		append_work( t );
	}
	else if( e.which == 120 )// F9
	{
		delete_work( t );
	}
	else if( e.ctrlKey && e.shiftKey && e.which == 70 )// ctrl+shift+f
	{
		activeDiv.html( htmlfilter( activeDiv.html() ) );
	}
}

var activeDiv;

function show_formater( div )
{
	activeDiv = $( div );
}

function buttonClickHandler( type )
{
	var t = $( "#__WORK_TABLE" );

	if( type == 1 )
	{
		submit_work( t );
	}
	else if( type == 2 )
	{
		append_work( t );
	}
	else if( type == 3 )
	{
		delete_work( t );
	}
}

/**
 * 检测工作表是否为空
 * 
 * @param flag true-工作表清空时补上说明行。false-增加工作记录时去除说明行。
 */
function check_empty( t, flag )
{
	if( flag )
	{
		t.append( "<tr id='no-work'><td colspan='4'>暂无工作日志记录。</td></tr>" );
	}
	else
	{
		t.find( "#no-work" ).remove();
	}
}

function append_work( t, time, title, content )
{
	check_empty( t, false );

	time = time != undefined ? time : "";
	title = title != undefined ? title : "任务名称";
	content = content != undefined ? content : "工作内容详细信息";

	var h = "<tr>" + "<td align='center' style='cursor:pointer;'><input type='checkbox' /></td>"
			+ "<td rel='select_time' align='center'><span>" + time + "</span><p class='caption'></p></td>"
			+ "<td><div contenteditable='true' onfocus='show_formater(this)'>" + title + "</div></td>"
			+ "<td><div contenteditable='true' onfocus='show_formater(this)'>" + content + "</div></td></tr>";
	t.append( h );

	// 计算时间间隔
	if( time != "" )
	{
		timetd = t.find( "tr:last > td[rel=select_time]" );
		update_selected_text_hour();
	}

	// 点击单元格可快捷切换选择状态，因为选择框太小
	t.find( "tr:last > td:has(input[type=checkbox])" ).bind( "click", tdChecked );
	t.find( "tr:last > td > input[type=checkbox]" ).bind( "click", function( e )
	{
		e.stopPropagation();
		tdChecked( e );
	} );

	// 时间选择器弹出事件
	t.find( "tr:last > td[rel=select_time]" ).bind( "click", function( e )
	{
		bind_select_timer( e, $( this ) );
	} );
}

function bind_select_timer( e, td )
{
	e.stopPropagation();
	show_time_selecter( td );
	init_to_timer( td );
	body_get_focus( e );
}

/**
 * 点击单元格可快捷切换选择状态，因为选择框太小
 * 
 * @param e event
 */
function tdChecked( e )
{
	var chk = $( this ).find( ":checkbox" );
	var checked = chk.prop( "checked" );
	chk.prop( "checked", !checked );
}

function delete_work( t )
{
	t.find( "tr:has(td:first > input:checked)" ).each( function()
	{
		$( this ).find( "td[rel=select_time]" ).unbind( "click" );
		$( this ).remove();
	} );

	if( t.find( "tr" ).length == 1 )
		check_empty( t, true );
}

function submit_work( t )
{
	var info = new Array();
	var right = true;

	t.find( "tr:has(td[rel=select_time])" ).each( function()
	{
		var d = {};
		d.time = $( this ).find( "> td" ).eq( 1 ).find( "span" ).text();
		//d.title = $( this ).find( "> td" ).eq( 2 ).find( "div" ).text();
		//d.content = $( this ).find( "> td" ).eq( 3 ).find( "div" ).html();
		d.title = htmlfilter( $( this ).find( "> td" ).eq( 2 ).find( "div" ).html() );
		d.content = htmlfilter( $( this ).find( "> td" ).eq( 3 ).find( "div" ).html() );
		
		if( d.time == "" )
		{
			infopad.msg( "任务时间段未选择。" );
			right = false;
			return false;
		}
		if( d.title == "" )
		{
			infopad.msg( "任务名称未填写。" );
			right = false;
			return false;
		}
		if( d.content == "" )
		{
			infopad.msg( "任务详情未填写。" );
			right = false;
			return false;
		}
		info.push( d );
	} );

	if( !right )
		return;

	// 图片列表
	var imgstr = $("#all_words").val();

	var json = JSON.stringify( info );

	submitter.post( contextPath+"/index/addWork.json", { content: json, images: imgstr, date: date }, function( d )
	{
		setTimeout(function(){
			window.location.href=contextPath+"/index/work_today.htm";
		},1000);
	}, "json" );
}
